import random
import time

from sam.util.fileUtil2 import write_file_quick
from sam.util.httpUtil import get_web_driver
from sam.util.strUtil import text_plain_str


class WeiBoSearch(object):
    def __init__(self, current_search_topic):
        super().__init__()
        self.browser = get_web_driver(headless=False, images_less=False)
        self.current_page_num = 0
        self.total_page_num = 0
        self.current_search_topic = current_search_topic
        self.transfer_num = 0
        self.comment_num = 0

    def __del__(self):
        print(f"转载数：{self.transfer_num}")
        print(f"评论数：{self.comment_num}")
        if self.browser:
            self.browser.quit()
            print("无图浏览器退出")

    def login(self):
        self.browser.get("https://weibo.com/")
        time.sleep(5)
        element1 = self.browser.find_element_by_css_selector(
            '#pl_login_form > div > div.info_header > div > a:nth-child(2)')
        self.browser.execute_script("arguments[0].click();", element1)
        time.sleep(5)
        print("ok")

    def open_search(self):
        self.current_page_num = 1
        # url = f"https://s.weibo.com/weibo?q={self.current_search_topic}&scope=ori&suball=1&Refer=g"
        url = f"https://s.weibo.com/weibo?q=%23{self.current_search_topic}%23&typeall=1&suball=1&Refer=g"
        print(f"将要访问: {url}")
        self.browser.get(url)
        time.sleep(5)
        li_list = self.browser.find_elements_by_css_selector(
            "#pl_feedlist_index > div.m-page > div > span > ul >li ")
        self.total_page_num = len(li_list)
        print(f"共有 {self.total_page_num} 页")

        self.handle_next_page()

    def parse_p_list(self, p_list):
        std_content = []
        for p in p_list:
            if p.text:
                std_str = text_plain_str(p.text)
                if "收起d" in std_str:
                    std_str = std_str.replace("收起d", "")
                std_content.append([std_str])
        else:
            write_file_quick(data_list=std_content, export_file_name=f"{self.current_search_topic}",
                             optional="append")

    def handle_next_page(self):
        while self.current_page_num <= self.total_page_num:
            # url = f"https://s.weibo.com/weibo?q={self.current_search_topic}&scope=ori&suball=1&Refer=g&page={self.current_page_num}"
            url = f"https://s.weibo.com/weibo?q=%23{self.current_search_topic}%23&typeall=1&suball=1&Refer=g&page={self.current_page_num}"
            print(f"将要访问: {url}")
            self.browser.get(url)
            time.sleep(random.randint(10, 20))

            # 统计
            transfer_element_list = self.browser.find_elements_by_css_selector(
                "div.card-act > ul > li:nth-child(1) > a")
            for transfer_element in transfer_element_list:
                transfer = transfer_element.text.strip()
                if transfer.isnumeric():
                    self.transfer_num += int(transfer)

            comment_element_list = self.browser.find_elements_by_css_selector(
                "div.card-act > ul > li:nth-child(2) > a")
            for comment_element in comment_element_list:
                comment = comment_element.text.strip()
                if comment.isnumeric():
                    self.comment_num += int(comment)

            # 打开 展开全文
            print("展开 展开全文")
            a_list = self.browser.find_elements_by_css_selector(
                "#pl_feedlist_index > div > div > div.card > div.card-feed > div.content > p > a[action-type]")
            for a in a_list:
                if "展开c" == a.text:
                    self.browser.execute_script("arguments[0].click();", a)
            print("处理本页的文本")
            # p_list = self.browser.find_elements_by_css_selector(
            #     "#pl_feedlist_index > div > div > div > div.card-feed > div.content > p.txt")
            # self.parse_p_list(p_list)

            print(f"完成第 {self.current_page_num} 页, 转载数累计: {self.transfer_num},  评论数累计: {self.comment_num}")
            self.current_page_num += 1
            self.handle_next_page()

    def search(self):
        self.login()
        self.open_search()


if __name__ == "__main__":
    bo = WeiBoSearch("我向许多人打听过你")
    bo.search()
